package com.bestcem.xm.survey.controller;

import cn.hutool.core.lang.ObjectId;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.survey.controller.vo.SurveyColumnVo;
import com.bestcem.xm.survey.entity.SurveyCondition;
import com.bestcem.xm.survey.entity.SurveyExtParameter;
import com.bestcem.xm.survey.entity.SurveyFilter;
import com.bestcem.xm.survey.entity.SurveyRespondentExportRecord;
import com.bestcem.xm.survey.service.*;
import com.bestcem.xm.survey.util.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.bestcem.xm.survey.enums.RespondentStatusEnum.RESPONDENT_STATUS_FINISH;
import static com.bestcem.xm.survey.util.SurveyConstant.RESPONDENT_FORMAL_SOURCE;

@Slf4j
@Api(tags = "答卷数据")
@RestController
@RequiredArgsConstructor
@RequestMapping("/survey/")
public class SurveyRespondentController {
    private @NonNull SurveyCommonService surveyCommonService;
    private @NonNull SurveyColumnService surveyColumnService;
    private @NonNull SurveyExtParameterService surveyExtParameterService;
    private @NonNull SurveyRespondentExportRecordService surveyRespondentExportRecordService;
    private @NonNull SurveyConditionService surveyConditionService;

    @ApiOperation(value = "获取答卷数据字段")
    @GetMapping(value = {"/respondents/v1/{project_id:[a-fA-F0-9]{24}}/columns/"})
    public XmResultJson<List<SurveyColumnVo>> getSurveyColumns(@PathVariable(value = "project_id") String projectId, HttpServletRequest request) {
        JSONObject args = JSONObject.parseObject(JSON.toJSONString(request.getParameterMap()));
        String orgId = SecurityContextHolder.getOrgId();
        return XmResultJson.success(surveyCommonService.getColumnsNeDelete(projectId, args, orgId));
    }

    @ApiOperation(value = "设置答卷数据字段显示/隐藏")
    @PutMapping(value = {"/respondents/v1/{project_id:[a-fA-F0-9]{24}}/columns/", "/respondents/v1/{project_id:[a-fA-F0-9]{24}}/columns/{c_id:[a-fA-F0-9]{24}}"})
    public XmResultJson<JSONObject> putSurveyColumns(@PathVariable(value = "project_id") String projectId, @PathVariable(value = "c_id", required = false) String surveyColumnId, @RequestBody JSONObject param) {
        return XmResultJson.success(surveyColumnService.putSurveyColumns(surveyColumnId, projectId, param));
    }

    @ApiOperation(value = "获取项目外部参数")
    @GetMapping(value = {"/projects/{project_id:[a-fA-F0-9]{24}}/extparameters/"})
    public XmResultJson<SurveyExtParameter> getExtparameters(@PathVariable(value = "project_id") String projectId, HttpServletRequest request) {
        JSONObject args = JSONObject.parseObject(JSON.toJSONString(request.getParameterMap()));
        return XmResultJson.success(surveyExtParameterService.getExtparameters(projectId, args));
    }

    @ApiOperation(value = "恢复/批量恢复删除状态的答卷数据")
    @PutMapping(value = {"/v2/projects/{project_id:[a-fA-F0-9]{24}}/resume/", "/v2/projects/{project_id:[a-fA-F0-9]{24}}/resume/{seq}"})
    public XmResultJson<Map<String, Integer>> putResume(@PathVariable(value = "project_id") String projectId, @PathVariable(value = "seq", required = false) String seq, @RequestBody(required = false) JSONObject param) {
        return XmResultJson.success(surveyColumnService.putResume(projectId, seq, param));
    }

    @ApiOperation(value = "删除/批量删除答卷数据")
    @PutMapping(value = {"/v2/projects/{project_id:[a-fA-F0-9]{24}}/discard/", "/v2/projects/{project_id:[a-fA-F0-9]{24}}/discard/{seq}"})
    public XmResultJson<Map<String, Integer>> putDiscard(@PathVariable(value = "project_id") String projectId, @PathVariable(value = "seq", required = false) String seq, @RequestBody(required = false) JSONObject param) throws Exception {
        return XmResultJson.success(surveyColumnService.putDiscard(projectId, seq, param));
    }

    @ApiOperation(value = "获取答卷数据筛选条件")
    @GetMapping(value = {"/v2/projects/{project_id:[a-fA-F0-9]{24}}/filter/"})
    public XmResultJson<?> getFilter(@PathVariable(value = "project_id") String projectId) {
        SurveyFilter filter = surveyColumnService.getFilter(projectId);
        JSONObject ret = new JSONObject();
        ret.put("data", Objects.isNull(filter) ? new JSONObject() : filter);
        return XmResultJson.success(ret);
    }

    @ApiOperation(value = "设置答卷数据筛选条件")
    @PutMapping(value = {"/v2/projects/{project_id:[a-fA-F0-9]{24}}/filter/"})
    public XmResultJson<?> putFilter(@PathVariable(value = "project_id") String projectId, @RequestBody JSONObject param) {
        JSONObject args = JSONObject.parseObject(JSON.toJSONString(param));
        surveyColumnService.putFilter(projectId, args);
        return XmResultJson.success();
    }

    @ApiOperation(value = "答卷数据-导出记录")
    @GetMapping(value = {"/respondents/v2/export/record/{id:[a-fA-F0-9]{24}}", "/respondents/v2/export/record/"})
    public XmResultJson<Object> getExportRecord(@ApiIgnore Page<SurveyRespondentExportRecord> page, @PathVariable(value = "id", required = false) String id, HttpServletRequest request) {
        //当url指定id时，直接查询该id的答卷数据导出记录，忽略其他筛选参数
        //当url没有指定id时，返回分页查询结果，参数在query中
        if (ObjectId.isValid(id)) {
            return XmResultJson.success(surveyRespondentExportRecordService.getOneRespondentexportrecord(id));
        }
        JSONObject args = JSONObject.parseObject(JSON.toJSONString(request.getParameterMap()));
        if (!PageUtil.isPageQuery(request)) {
            return XmResultJson.success(surveyRespondentExportRecordService.getRespondentExportRecordList(args));
        } else {
            return XmResultJson.success(surveyRespondentExportRecordService.getExportRecordPage(page, args));
        }
    }

    @ApiOperation(value = "答卷数据-删除导出记录")
    @DeleteMapping(value = {"/respondents/v2/export/record/{id:[a-fA-F0-9]{24}}", "/respondents/v2/export/record/"})
    public XmResultJson<Object> deleteExportRecord(@PathVariable(value = "id", required = false) String id, @RequestBody JSONObject param) {
        //单个删除时，直接在url最后指定id
        //批量删除时，在参数中指定idList
        if (ObjectId.isValid(id)) {
            return XmResultJson.success(surveyRespondentExportRecordService.deleteOneRespondentexportrecord(id));
        }
        return XmResultJson.success(surveyRespondentExportRecordService.deleteRespondentexportrecordList(param));
    }

    @ApiOperation(value = "答卷数据-答卷详情")
    @GetMapping(value = {"/respondents/v1/detail/{seq}/"})
    public XmResultJson<JSONObject> getRespondentsDetail(@PathVariable(value = "seq") String seq, HttpServletRequest request) {
        JSONObject args = JSONObject.parseObject(JSON.toJSONString(request.getParameterMap()));
        return XmResultJson.success(surveyColumnService.getRespondentsDetail(seq, args));
    }

    @ApiOperation(value = "答卷数据-答卷详情")
    @GetMapping(value = {"/respondents/v1/{project_id:[a-fA-F0-9]{24}}/detail/{seq}/"})
    public XmResultJson<JSONObject> getRespondentsDetail(@PathVariable(value = "seq") String seq,
                                                         @PathVariable(value = "project_id") String projectId, HttpServletRequest request) {
        JSONObject args = JSONObject.parseObject(JSON.toJSONString(request.getParameterMap()));
        return XmResultJson.success(surveyColumnService.getRespondentsDetail(seq, args));
    }

    @ApiOperation(value = "答卷数据-导出")
    @PostMapping(value = {"/respondents/v2/{id:[a-fA-F0-9]{24}}/export"})
    public XmResultJson<Map<String, String>> respondentsV12Excel(@PathVariable(value = "id", required = false) String id, @RequestBody JSONObject param) {
        return XmResultJson.handleServiceResult(surveyRespondentExportRecordService.respondentsV12Excel(id, param));
    }

    @GetMapping(value = {"/respondents/v1/{project_id:[a-fA-F0-9]{24}}/update/"})
    public XmResultJson<JSONObject> getRespondentsAnswers(@PathVariable(value = "project_id") String projectId, HttpServletRequest request) {
        return XmResultJson.success(surveyColumnService.getRespondentsAnswers(projectId, request));
    }

    @ApiOperation(value = "答卷数据-修改答案")
    @PutMapping(value = {"/respondents/v1/{project_id:[a-fA-F0-9]{24}}/update/"})
    public XmResultJson<JSONObject> putRespondentsAnswers(@PathVariable(value = "project_id") String projectId, @RequestBody JSONObject param) {

        return XmResultJson.success(surveyColumnService.putRespondentsAnswers(projectId, param));
    }

    @ApiOperation(value = "答卷数据-回收站彻底删除")
    @DeleteMapping(value = {"/v2/respondents/{id:[a-fA-F0-9]{24}}", "/v2/respondents/"})
    public XmResultJson<Map<String, Integer>> deleteRespondents(@PathVariable(value = "id", required = false) String id, @RequestBody JSONObject param) {
        //单个删除时，直接在url最后指定id
        //批量删除时，在参数中指定seqList
        return XmResultJson.success(surveyColumnService.deleteRespondents(id, param));
    }

    @ApiOperation(value = "答卷数据-回收站")
    @PostMapping(value = {"/v2/respondents/{id:[a-fA-F0-9]{24}}", "/v2/respondents/"})
    public XmResultJson<Object> postRespondents(@PathVariable(value = "id", required = false) String id, @RequestBody JSONObject param) {
        //单个删除时，直接在url最后指定id
        //批量删除时，在参数中指定seqList
        if (ObjectId.isValid(id)) {
            return XmResultJson.success(surveyColumnService.postRespondentsById(id, param));
        }
        return XmResultJson.success(surveyColumnService.postRespondentsPage(param));
    }

    @ApiOperation(value = "答卷数据")
    @PostMapping(value = {"/respondents/v1/{id:[a-fA-F0-9]{24}}", "/respondents/v1/"})
    public XmResultJson<Map<String, Object>> respondentsV1(@PathVariable(value = "id", required = false) String id, @RequestBody JSONObject param) {
        return XmResultJson.success(surveyRespondentExportRecordService.respondentsV1(id, param));
    }

    @ApiOperation(value = "答卷数据-导出进度条百分比")
    @PostMapping(value = {"/respondents/v2/export/progress/"})
    public XmResultJson<Map<String, Object>> rspdExportProgress(@RequestBody JSONObject param) {
        return XmResultJson.success(surveyRespondentExportRecordService.rspdExportProgress(param));
    }

    @GetMapping(value = {"/v2/projects/{project_id:[a-fA-F0-9]{24}}/conditions"})
    public XmResultJson<List<SurveyCondition>> condition(@PathVariable(value = "project_id") String projectId) {
        return XmResultJson.success(surveyConditionService.condition(projectId));
    }

    @ApiOperation(value = "答卷数据-更多-导出附件")
    @GetMapping(value = {"/respondents/v2/{project_id:[a-fA-F0-9]{24}}/attachment/{seq:[0-9]*}/"})
    public XmResultJson<?> respondentsV12Attachment(@PathVariable(value = "project_id") String projectId, @PathVariable(value = "seq") String seq) {
        return XmResultJson.handleServiceResult(surveyRespondentExportRecordService.respondentsV12Attachment(projectId, seq));
    }

    // /api/survey/v2/respondents/?member_id=64f69e9403d25801cfd17fa0&status=0,1,2,3,6,7,107,10&withProject=1&page=1&rowsPerPage=5&_=1693884088843
    @ApiOperation(value = "联系人答卷数据")
    @GetMapping(value = {"/v2/respondents/{id:[a-fA-F0-9]{24}}", "/v2/respondents/"})
    public Object getRespondentsPage(@PathVariable(value = "id", required = false) String id, HttpServletRequest request) {
        if (Objects.nonNull(id)) {
            log.warn("getRespondents by id found");
        }
        if (!PageUtil.isPageQuery(request)) {
            log.warn("getRespondents list found");
        }

        // TODO 上面2个暂时没发现调用地方
        Map<String, String> paramsMap = ServletUtil.getParamMap(request);
        paramsMap.put("status", RESPONDENT_STATUS_FINISH.getValue().toString());
        paramsMap.put("source", RESPONDENT_FORMAL_SOURCE.stream().map(String::valueOf).collect(Collectors.joining(",")));
        JSONObject params = new JSONObject();
        params.putAll(paramsMap);
        return surveyColumnService.postRespondentsPage(params);
    }

}